loginApp.controller('configureController', function($http, $rootScope, $scope, $location, configureService, loginService) {

    // recuperation des configurations existantes
    configureService.query(function(configures) {
        $scope.configures = configures;
    });

    $scope.loggedIn = loginService.isAuthenticated();

    $scope.editConfigure = function(configure) {
        if (configure === 'new') {
            $scope.newConfigure = true;
            $scope.configure = {
                username: loginService.getUserName(),
                name: '',
                hostname: '',
                port: '',
                database: '',
                user: '',
                password: ''
            };
        } else {
            $scope.newConfigure = false;
            $scope.configure = configure;
        }
    };

    $scope.save = function() {
        if (!$scope.configure._id) {
            var newConfigure = new configureService($scope.configure);
            newConfigure.$create(function() {
                $scope.configures.push(newConfigure);
                $rootScope.$emit('configure change');
            });
        } else {
            $scope.configures.forEach(function(e) {
                if (e._id === $scope.configure._id) {
                    console.log(e);
                    e.$update(function() {
                        $rootScope.$emit('configure change');
                    });
                }
            });
        }
    };

    $scope.delete = function() {
        $scope.configures.forEach(function(e, index) {
            if (e._id == $scope.configure._id) {
                $scope.configure.$destroy({
                    id: $scope.configure._id
                }, function() {
                    $scope.configures.splice(index, 1);
                    $rootScope.$emit('configure change');
                });
            }
        });
    };
});